import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ConfigService } from '@kylin/config';
import { CacheService } from './cache.service';
import { NzMessageService } from 'ng-zorro-antd';
import { CustomRequestParams } from '@kylin/class';
import { RouterService } from '@kylin/router';

@Injectable()

export class HttpService {

    private hostname: string;
    private lastTimeFetchAccessToken = 0;

    constructor(private http: HttpClient,
        private cacheService: CacheService,
        private httpConfigService: ConfigService,
        private message: NzMessageService,
        private routerService: RouterService
    ) {
        this.hostname = this.httpConfigService.hostname;
    }

    get(path: string, params?: CustomRequestParams): Promise<any> {
        // const accessTokenState = this.checkAccessTokenExpirationTime();
        // if (!accessTokenState) {
        //     const newAccessToken = await this.fetchNewAccessToken();
        // }
        return new Promise((resolve, reject) => {
            this.http.get(path, { 'params': params }).toPromise()
                .then(res => {
                    resolve(res);
                })
                .catch(err => {
                    console.warn('err');
                    console.warn(err);
                    reject(err);
                });
        });
    }

    delete(path: string, params?: CustomRequestParams): Promise<any> {
        return new Promise((resolve, reject) => {
            this.http.delete(path, { 'params': params }).toPromise()
                .then(res => {
                    resolve(res);

                })
                .catch(err => {
                    console.warn('err');
                    console.warn(err);
                    reject(err);
                });
        });
    }

    post(path: string, body: any, params?: CustomRequestParams): Promise<any> {
        return new Promise((resolve, reject) => {
            this.http.post(path, body, { 'params': params }).toPromise()
                .then(res => {
                    resolve(res);
                })
                .catch(err => {
                    console.warn('err');
                    console.warn(err);
                    reject(err);
                });
        });
    }

    put(path: string, body?: any, params?: CustomRequestParams): Promise<any> {
        return new Promise((resolve, reject) => {
            this.http.put(path, body, { 'params': params }).toPromise()
                .then(res => {
                    resolve(res);
                })
                .catch(err => {
                    console.warn('err');
                    console.warn(err);
                    reject(err);
                });
        });
    }

    /**
     * 目前只有网络问题导致的HTTP请求无法发出才会走catch
     */
    private handleError() {
        this.cacheService.remove('siderData');
        this.routerService.navigate('/login');
        this.message.warning('您的登陆信息已经失效,请重新登陆!');
    }

    private checkAccessTokenExpirationTime(): boolean {
        const expires_time = this.cacheService.get('expires_time');
        const current_time = new Date().getTime();
        if (current_time > expires_time && (current_time - this.lastTimeFetchAccessToken > 60000)) {
            return true;
        } else {
            return false;
        }
    }

    // todo 测试完成以后 这个方法需要设置为私有,
    fetchNewAccessToken(): Promise<string> {
        return new Promise((resolve, reject) => {
            this.lastTimeFetchAccessToken = new Date().getTime();
            const refresh_token = this.cacheService.get('refresh_token');
            this.http.post('/oauth/user/token', {
                refreshToken: refresh_token,
                clientId: 'system',
                clientSecret: 'system',
                grantType: 'refresh_token'
            }).toPromise()
                .then(res => {
                    if (res['resp_code'] === '10000') {
                        const newAccessToken = res['data'].access_token;
                        this.cacheService.set('access_token', newAccessToken);
                        const expires_time = new Date().getTime() + res['data'].expires_in * 1000;
                        this.cacheService.set('expires_time', expires_time);
                        resolve(newAccessToken);
                    } else {
                        // todo 开发完成以后这里alert需要删除
                        resolve('');
                        alert('获取access_token失败,跳转到Login');
                        this.routerService.navigate('/login');
                    }
                })
                .catch(err => {
                    resolve('');
                    alert('获取access_token失败,跳转到Login');
                    this.routerService.navigate('/login');
                })
        })
    }
}
